package com.xiaolun.netty.codec2;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

//public class NettyServerHandler extends ChannelInboundHandlerAdapter {
public class NettyServerHandler extends SimpleChannelInboundHandler<MyDataInfo.MyMessage> {

	//读取数据实际(这里我们可以读取客户端发送的消息)
	@Override
	public void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyMessage msg) throws Exception {
		//根据dataType 来显示不同的信息
		MyDataInfo.MyMessage.DataType dataType = msg.getDataType();
		if (dataType == MyDataInfo.MyMessage.DataType.StudentType) {
			MyDataInfo.Student student = msg.getStudent();
			System.out.println("学生id=" + student.getId() + " 学生名字=" + student.getName());
		} else if (dataType == MyDataInfo.MyMessage.DataType.WorkerType) {
			MyDataInfo.Worker worker = msg.getWorker();
			System.out.println("工人的名字=" + worker.getName() + " 年龄=" + worker.getAge());
		} else {
			System.out.println("传输的类型不正确");
		}
	}

	//数据读取完毕
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(>^ω^<)喵1", CharsetUtil.UTF_8));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}
